package com.scalar.chiptrack.operations.dataentry.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.dataentry.InTransitLots;
import com.scalar.chiptrack.operations.dataentry.dao.MRBReleaseDAO;
import com.scalar.chiptrack.operations.dataentry.forms.MRBReleaseForm;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.NotificationSetupDAO;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.StringUtils;

/**
 * Created by Chandra Shekar.
 * Date: Jun 20, 2005
 * Time: 6:08:08 PM
 */
public class MRBReleaseAction  extends ChipTrackAction
{
    private static final String ACTION_NAME = "/mrbRelease.do";

    public ActionForward execute( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response )
            throws Exception
    {
        HttpSession session = request.getSession();

        User user = ( User ) session.getAttribute( SessionKeys.USER_KEY );

        if ( user == null )
        {
            session.setAttribute( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString() );
            return ( mapping.findForward( "login" ) );
        }

        MRBReleaseForm mrbReleaseForm = ( MRBReleaseForm ) form;

        if ( mrbReleaseForm == null )
        {
            mrbReleaseForm = new MRBReleaseForm();
        }

        String action = request.getParameter( "action" );
        if ( action == null )
        {
            action = "";
        }
        request.setAttribute( "action", action );
        HashMap errors = new HashMap();
        HashMap info = new HashMap();

        if ( user != null && user.isActionAllowed ( Functionality.MRB_RELEASE, User.USER_ACTION_MODIFY ) )
        {
            request.setAttribute ( "showMessage", "FALSE" );
        }
        else
        {
            request.setAttribute ( "showMessage", "TRUE" );
        }


        if ( action.equals( "" ) )
        {
            ArrayList releaseLotsList = MRBReleaseDAO.getAllMRBReleaseLots();
            mrbReleaseForm.setMrbReleaseLotsList( releaseLotsList );
            request.setAttribute( "releaseLotsList", releaseLotsList );
            ArrayList moveToOptions = MRBReleaseDAO.getMoveToOptions();
            request.setAttribute ( "moveToOptions", moveToOptions );
            return mapping.findForward( "success" );
        }

        if ( action.equals( "save" ) )
        {
            ArrayList releaseList = new ArrayList();
            InTransitLots   inTransitLots = null;
            boolean success = false;
            releaseList = mrbReleaseForm.getMrbReleaseLotsList();
            DBTransaction dbTransaction = null;
            if ( releaseList.size() > 0 )
            {
                try
                {

                    dbTransaction = DBTransaction.getInstance();
                    dbTransaction.begin();
                    MRBReleaseDAO.updateReleaseMRBStatus ( dbTransaction, releaseList );
                    // To update the MRB Limit status
                    for( int i= 0; i < releaseList.size(); i++ )
                    {
                        inTransitLots = ( InTransitLots )releaseList.get(i);
                        if ( Constants.MRBRELEASE_MOVE_TO_RELEASE.equalsIgnoreCase( inTransitLots.getMoveTo() ) && inTransitLots.isChecked() )
                        {
                            MRBReleaseDAO.insertSortBinReleaseLots( dbTransaction, inTransitLots );
                        }
                    }
                    success = true;
                    request.setAttribute( SessionKeys.INFO_MESSAGES, info );
                }
                catch ( ScalarException se )
                {
                    se.getRootCause().printStackTrace();
                    errors.put( "Internal Server Error:", "Could not Release the Lots " );
                    request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
                }
                finally
                {
                    if ( success == true )
                    {
                        if ( dbTransaction != null )
                        {
                            dbTransaction.commit ();
                        }
                        info.put( "Selected Lots are Released Successfully ", null );
                    }
                    else
                    {
                        errors.put( "Selected Lots Couldn't be Released Successfully ", null );
                        dbTransaction.rollback ();
                    }
                }
                try
                {
                    notifyAllReceipients ( user, releaseList );
                    info.put ( "Notification Email has been sent to all recipients", null );
                }
                catch ( Exception e )
                {
                    errors.put ( "Internal Server Error", "Could not send notification emails" );
                }
            }
            ArrayList releaseLotsList = MRBReleaseDAO.getAllMRBReleaseLots();
            mrbReleaseForm.setMrbReleaseLotsList( releaseLotsList );
            request.setAttribute( "releaseLotsList", releaseLotsList );
            request.setAttribute ( "moveToOptions", MRBReleaseDAO.getMoveToOptions() );

            return mapping.findForward( "success" );
        }

       return mapping.findForward( "success" );
    }

    private void notifyAllReceipients ( User user, ArrayList releaseList ) throws Exception
    {
        String subject = "MRB Release notification";
        String message = getNotificationMessage ( releaseList );
        String[] to   = NotificationSetupDAO.loadEmailsByType( Constants.NOTIFICATION_EMAIL_TYPE_FOR_SORT_RELEASE );
        String toEmails = StringUtils.concatStrings ( to, Mailer.EMAIL_SEPARATOR );
        String fromEmail = user.getEmail();
        Mailer.send (fromEmail, toEmails, null, null, subject, message, null, Mailer.CONTENT_TYPE_HTML, false);
    }
    private String getNotificationMessage ( ArrayList releaseList )
    {
        StringBuffer notificationMessage = new StringBuffer( "<HTML><BODY>" );
        notificationMessage.append ( "<TABLE border='0' align='center'>" );
        notificationMessage.append ( "<TR bgcolor='#993333' align='center'><font color=\"#FFFFFF\">");
        notificationMessage.append ( "<TD bgcolor='#993333' style='color:white;'>Part Number</TD><TD style='color:white;'>Lot #</TD><TD style='color:white;'>Wafer Id</TD><TD style='color:white;'>Good Qty</TD><TD style='color:white;'>Comments</TD><TD style='color:white;'>Moved To</TD>");
        notificationMessage.append ( "</font></TR>");
        int releaseListSize =  ( releaseList == null ) ? 0 : releaseList.size();
        InTransitLots inTransitLots = null;
        for ( int i = 0; i < releaseListSize; i++ )
        {
            inTransitLots = ( InTransitLots )releaseList.get(i);
            if ( inTransitLots.isChecked() )
            {
                notificationMessage.append ( "<TR bgcolor='#DEE1E2'>" );
                notificationMessage.append ( "<TD>" + inTransitLots.getPartNumber() + "</TD>" );
                notificationMessage.append ( "<TD>" + inTransitLots.getLotNumber() + "</TD>" );
                notificationMessage.append ( "<TD>" + inTransitLots.getWaferId() + "</TD>" );
                notificationMessage.append ( "<TD>" + inTransitLots.getShipQty() + "</TD>" );
                notificationMessage.append ( "<TD>" + inTransitLots.getComments() + "</TD>" );
                notificationMessage.append ( "<TD>" );
                if ( Constants.MRBRELEASE_MOVE_TO_RELEASE.equalsIgnoreCase( inTransitLots.getMoveTo() ) )
                {
                    notificationMessage.append ( "Release" );
                }
                else if ( Constants.MRBRELEASE_MOVE_TO_RTV.equalsIgnoreCase( inTransitLots.getMoveTo() ) )
                {
                    notificationMessage.append ( "RTV" );
                }
                else if ( Constants.MRBRELEASE_MOVE_TO_MATRIX.equalsIgnoreCase( inTransitLots.getMoveTo() ) )
                {
                    notificationMessage.append ( "Matrix" );
                }
                else if ( Constants.MRBRELEASE_MOVE_TO_SCRAP.equalsIgnoreCase( inTransitLots.getMoveTo() ) )
                {
                    notificationMessage.append ( "Scrap" );
                }
                else if ( Constants.MRBRELEASE_MOVE_TO_ENGG.equalsIgnoreCase( inTransitLots.getMoveTo() ) )
                {
                    notificationMessage.append ( "Engg" );
                }
                notificationMessage.append ( "</TD>" );
                notificationMessage.append ( "</TR>" );
            }
        }
        notificationMessage.append ( "</TABLE>" );
        notificationMessage.append ( "</BODY></HTML>" );
        return notificationMessage.toString();
    }
}
